package com.project.forlearningdemo.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //shiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro内置过滤器
        /*
            anon 无需认证即可访问
            authc: 必须认证后才访问
            user: 必须拥有记住我功能才可访问
            perms: 拥有对某个资源的权限才可访问
            role: 拥有某个角色的资源才可访问
         */
        Map<String, String>  filter = new LinkedHashMap<>();
        //用户一共有4种权限:null(无权限), user(正常权限), vipu（高级权限）, admin（管理员权限）
        //perms[user:*] 用户--使用用户包括VIPU可以访问
        //perms[vipu:*] vip用户--
        // filter.put("/main.action", "perms[user:1]");
        filter.put("/user/**", "anon");

        bean.setFilterChainDefinitionMap(filter);
        //无权限后跳转的页面
        bean.setLoginUrl("/user/uauth");
        bean.setUnauthorizedUrl("/user/uauth");
        return bean;
    }

    //DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象，需要自定义类
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

}
